var area = document.getElementById("container");
var myImage = new Image()
area.ondragenter = function(ev) {
	showShadow();
    ev.preventDefault();

};
//prevent open pic
//must have
area.ondragover = function(ev) {
    ev.preventDefault();
};
//when 
area.ondrop = function(ev) {
    ev.preventDefault();
    var dt = ev.dataTransfer;
    var file = dt.files[0];

    //just can upload img
    var format = new RegExp('image/*')
    if(!format.test(file.type))
    {
        $('#buttom').before('<h2>Please upload image!!!</h2>');
        return ;        
    }

    //showimg
    // showImg(file);
    desShadow();
    // check this file md5
    //if exist ,send img tag
    //else upload

	getMd5(file,function(md5){

		var myImage = new Image();
		var flag = true;
        var exten = file.name.split('.').pop();
		//test this img is exist in server
		//to make sure send msg or upload
		try{
			myImage.src = 'http://7xo1fz.com1.z0.glb.clouddn.com/'+md5+'.'+exten;
		}catch(err){}
		myImage.onload=function(){
			//already exist
			showImg(myImage);
			var s = msg.value;
			s += "<img src='http://7xo1fz.com1.z0.glb.clouddn.com/"+md5+"."+exten+"'>";
			msg.value = s;
			flag = true;
		}
		myImage.onerror = function(){
			//no exist,upload
			// console.log("not exist");
			if(flag){
				upload(file,function(res){
					//return the img url
		        	// console.log(res);
		        	myImage.src = 'http://7xo1fz.com1.z0.glb.clouddn.com/'+md5+'.'+exten;//继续加载
		        	// $('#buttom').before('<p class="me">me  :  <img src="'+res+'"></p>')
		        })	
		        flag = false;
			}
		}
	})
};

//use ajax upload img
function upload(file,callback){

	// 检查是否支持FormData
　　if(window.FormData) {　
　　　　var formData = new FormData();
　　　　// 建立一个upload表单项，值为上传的文件
　　　　formData.append('img', file);
　　　　var xhr = new XMLHttpRequest();
　　　　xhr.open('POST', 'http://chat.spsilab.cn/upload');
　　　　// 定义上传完成后的回调函数
　　　　xhr.onload = function () {
　　　　　　if (xhr.status === 200) {
				// console.log(xhr.response);
            	// console.log(xhr.responseText);
            	callback(xhr.responseText);
　　　　　　} else {
// 　　　　　　　　console.log('出错了');
　　　　　　}
　　　　};
　　　　xhr.send(formData);
　　}

}

function showImg(img){
    var show_img = document.getElementById("show-img");
    show_img.appendChild(img);
}

function showShadow() {
	var shadow = document.getElementById("shadow");
	var p = document.createElement("p");
	p.innerText = "[+]";
	shadow.appendChild(p);
}

function desShadow() {
	var shadow = document.getElementById("shadow");
	shadow.innerHTML = "";
}

function desImg() {
	var show_img = document.getElementById("show-img");
	show_img.innerHTML = "";
}


function getMd5(file,callback){
        var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2097152,                             // Read in chunks of 2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();

    fileReader.onload = function (e) {
        spark.append(e.target.result);                   // Append array buffer
        currentChunk++;

    if (currentChunk < chunks) {
        loadNext();
    } else {
        callback(spark.end());  // Compute hash
    }
};

    fileReader.onerror = function () {
        // console.warn('oops, something went wrong.');
    };

    function loadNext() {
        var start = currentChunk * chunkSize,
        end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
       }
    loadNext();
}